import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { UserService } from 'src/modules/user/user.service';
import { IS_PUBLIC_KEY } from 'src/common/public.decorator';

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
    private userService: UserService,
  ) {}

  // 判断是否允许通过
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = Reflect.getMetadata(IS_PUBLIC_KEY, context.getHandler());
    if (isPublic) return true;

    const request = context.switchToHttp().getRequest();
    const token = this.extractToken(request);

    if (!token) {
      throw new UnauthorizedException('请先登录');
    }

    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: process.env.JWT_SECRET_KEY,
      });

      const user = await this.userService.findById(payload.userId);

      if (!user) {
        throw new UnauthorizedException('用户不存在');
      }

      request.user = {
        id: user._id,
        phone: user.phone,
        openid: user.openid,
      };
    } catch (err) {
      console.log('err', err);
      throw new UnauthorizedException('登录凭证已过期');
    }

    return true;
  }

  private extractToken(req: Request): string | undefined {
    return req.headers.authorization?.replace('Bearer ', '');
  }
}
